<template>
  <div class="form-customer-address">
    <biz-remote-select
      :field="field"
      :value="addressValue"
      :placeholder="placeholder || $t('common.form.placeHolder.customerAddress.pla1')"
      cleared
      :remote-method="searchAddressOuterHandler"
      @input="updateAddress"
      :mounted-search="true"
    >
    </biz-remote-select>
    <el-button type="plain-third" class="ml_12" @click="handleCreateAddress">{{ $t('common.base.create') }}</el-button>

    <!-- start 地址弹窗 -->
    <edit-address-dialog ref="editAddressDialogRef" :customer-id="customerId" />
    <!-- end 地址弹窗 -->
  </div>
</template>

<script>
// api
import { searchCustomerAddressForProduct } from '@src/api/ProductApi';
// mixin
import FormMixin from '@src/component/form/mixin/form';
// util
import { customerAddressSelectConversion } from '@src/util/conversionFunctionUtil.ts';
import _ from 'lodash';

import EditAddressDialog from '@src/modules/customer/view/operationDialog/EditAddressDialog.vue';

import { formatAddress } from 'pub-bbx-utils';
export default {
  name: 'form-customer-address',
  mixins: [FormMixin],
  components: {
    EditAddressDialog,
  },
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    clearable: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      addressValue: this.value || [],
      customerId: '',
      firstSearch: true,
    };
  },
  watch: {
    value: {
      handler(newValue) {
        if (!newValue) return;

        let addressValue = _.cloneDeep(newValue);

        if (Array.isArray(addressValue) && addressValue.length > 0) {
          this.addressValue = (addressValue || []).map(address => {
            
            if (!address) return;

            address.label = formatAddress(address);

            address.value = address?.id;
            return address;
          });
        } else {
          this.addressValue = [];
        }
      },
      immediate: true,
    },
  },
  mounted() {
    this.$eventBus.$on('task_create_or_edit.update_address', this.updateAddress);
  },
  beforeDestroy() {
    this.$eventBus.$off('task_create_or_edit.update_address', this.updateAddress);
  },
  methods: {
    /**
     * @description: 更新表单的值
     */
    updateAddress(newValue) {
      let address = Array.isArray(newValue) ? newValue : [newValue];
      this.inputForValue(address);
    },
    // 获取客户id
    getCustomerId() {
      let field = this.fields.find(item => item.formType == 'customer' || item.formType === 'projectCustomer');

      let customerValue = (field && this.formValue?.[field.fieldName]) ?? [];

      // 第一次进来&地址有值的时候不提示
      const firstTip = this.firstSearch && this.value?.length

      if (customerValue?.length <= 0 && (!firstTip)) {
        this.customerId = '';
        return this.$message.warning(this.$t('common.form.tip.chooseBeforeTips', { module: this.$t('common.base.customer') }));
      }
      return this.customerId = Array.isArray(customerValue) ? customerValue?.[0]?.id : '';
    },
    /**
     * @description 搜索地址 外层处理器
     * @param {Object} params 搜索参数
     */
    async searchAddressOuterHandler(params = {}) {
      params.customerId = this.getCustomerId();

      this.firstSearch = false

      // 没有客户id返回空
      if (!params.customerId) return [];

      return this.searchAddress(params);
    },

    /**
     * @description 搜索客户地址
     */
    async searchAddress(params = {}) {
      try {
        const result = await searchCustomerAddressForProduct(params);

        if (!result || !result.data.list) return;

        result.data.list = result.data.list.map(address => customerAddressSelectConversion(address));

        return result.data;
      } catch (error) {
        console.warn('task-edit-form: searchProduct -> error', error);
      }
    },
    // 新建
    handleCreateAddress() {
      this.getCustomerId()
      
      if(!this.customerId.length) return;

      this.$refs.editAddressDialogRef.openDialog();
    },
  },
};
</script>

<style lang="scss" scoped>
.form-customer-address {
  display: flex;
  flex-flow: row nowrap;
}
</style>
